package com.szrt.day20170504.ch07;

/**
 * 用Ticket类模拟100张票
 * 
 * @author zsrt
 *
 */
class TicketObject {

	private int ticketCounter=0;

	public int getTicketCounter() {
		return ticketCounter;
	}

	public void setTicketCounter(int ticketCounter) {
		this.ticketCounter = ticketCounter;
	}
	
	
	
	
}

/**
 * 售票窗口
 * 
 * @author zsrt
 *
 */
class Window extends Thread {

	private TicketObject ticketObject = null;

	public void setTicket(TicketObject ticketObject) {
		this.ticketObject = ticketObject;
	}

	@Override
	public void run() {
		sellTicket();
	}

	
	/**
	 * 买票
	 */
	@SuppressWarnings("static-access")
	public synchronized void  sellTicket() {
		for (int index = 1; index <= 100; index++) {
			int ticket = ticketObject.getTicketCounter();
			if (ticket >= 1) {
				try {
					System.out.println(Thread.currentThread().getName() + "开始买票：");
					Thread.currentThread().sleep(100);
					
					//取得当前的票号
					System.out.println(Thread.currentThread().getName() + "票号=" + ticket);
					
					ticketObject.setTicketCounter(ticket-1);
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}

		}

	}

}

public class TicketThread {
	
	
	public static void main(String[] args) {
		
		
		//1 初始化票
		
		TicketObject  ticketObject  = new TicketObject();
		ticketObject.setTicketCounter(100);
		
		Window w01 = new Window();
		w01.setTicket(ticketObject);
		
		Window w02 = new Window();
		w02.setTicket(ticketObject);
		
		
		Window w03 = new Window();
		w03.setTicket(ticketObject);
		
		w01.start();
		w02.start();
		w03.start();
	}

}
